#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "log.h"
#include "type.h"

void add_line_to_file(char *fileName, char *addStr)
{
    FILE *fp = fopen(fileName, "a");
    if (fp == NULL) {
        ERROR("Failed to open file %s", fileName);
        return;
    }
    fprintf(fp, "%s", addStr);
    fclose(fp);
}

void delete_line_from_file(char *fileName, int lineNumber)
{
    char line[MAX_BUFFER_LENGTH];
    int curLineNumber = 1;
    char tempFileName[] = "temp.txt";
    FILE *fp = fopen(fileName, "r");
    if (fp == NULL) {
        ERROR("Failed to open file %s", fileName);
        return;
    }

    FILE *tmpFp = fopen(tempFileName, "w");
    if (tmpFp == NULL) {
        ERROR("Failed to create temp file");
        fclose(fp);
        return;
    }

    while (fgets(line, MAX_BUFFER_LENGTH, fp) != NULL) {
        if (curLineNumber != lineNumber) {
            fprintf(tmpFp, "%s", line);
        }
        curLineNumber++;
    }
    fclose(fp);
    fclose(tmpFp);
    remove(fileName);
    rename(tempFileName, fileName);
}

S32 find_line_in_file(char *fileName, char *searchStr)
{
    char line[MAX_BUFFER_LENGTH];
    int curLineNumber = 1;
    FILE *fp = fopen(fileName, "r");
    if (fp == NULL) {
        ERROR("Failed to open file %s", fileName);
        return FAILURE;
    }

    while (fgets(line, MAX_BUFFER_LENGTH, fp) != NULL) {
        if (strstr(line, searchStr) != NULL) {
            DUMP("Line %d: %s", curLineNumber, line);
            fclose(fp);
            return curLineNumber;
        }
        curLineNumber++;
    }
    fclose(fp);
    return FAILURE;
}

S32 modify_line_in_file(char *fileName, int lineNumber, char *newStr)
{
    char line[MAX_BUFFER_LENGTH];
    int curLineNumber = 1;
    FILE *fp = fopen(fileName, "r");
    if (fp == NULL) {
        ERROR("Failed to open file %s\n", fileName);
        return FAILURE;
    }
    char tempFileName[] = "temp.txt";
    FILE *tmpFp = fopen(tempFileName, "w");
    if (tmpFp == NULL) {
        ERROR("Failed to create temp file\n");
        fclose(fp);
        return FAILURE;
    }

    while (fgets(line, MAX_BUFFER_LENGTH, fp) != NULL) {
        if (curLineNumber == lineNumber) {
            fprintf(tmpFp, "%s\n", newStr);
        } else {
            fprintf(tmpFp, "%s", line);
        }
        curLineNumber++;
    }
    fclose(fp);
    fclose(tmpFp);
    remove(fileName);
    rename(tempFileName, fileName);
    return SUCCESS;
}

